package cn.may.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author May
 * @date 2020/12/03 18:16
 */
public class UploadUtil {
    /**
     * 文件上传
     * @author mayuanbao
     * @date 2020/12/03 18:22
     * @param file file
     * @param filePath 文件上传后的路径
     * @return java.lang.String
     */
    public static String upload(MultipartFile file, String filePath) {
        if (file.isEmpty()) {
            return "您没有选择任何文件";
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        String[] names = new String[2];
        if (fileName != null) {
            names = fileName.split("\\.");
        }
        try {
            // 创建文件
            File dest = new File(filePath + names[0] + System.currentTimeMillis() + names[1]);
            // 检测目录是否存在，不存在则新建
            if (!dest.getParentFile().exists()) {
                boolean mkdirs = dest.getParentFile().mkdirs();
            }
            // 写入磁盘
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 多文件上传
     * @author mayuanbao
     * @date 2020/12/03 18:41
     * @param files files
     * @param filePath 文件上传后的路径
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    public static Map<String, String> multiUpload(List<MultipartFile> files, String filePath) {
        Map<String, String> map = new LinkedHashMap<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String[] names = new String[2];
            if (fileName != null) {
                names = fileName.split("\\.");
            }
            File dest = new File(filePath + names[0] + System.currentTimeMillis() + names[1]);
            try {
                file.transferTo(dest);
                map.put(fileName, "上传成功");
            } catch (IOException e) {
                map.put(fileName, "上传失败");
            }
        }
        return map;
    }
}
